package gminet.infra.web;

import gminet.infra.toolkit.Cryptography;

import javax.servlet.http.HttpSession;

public class SessionAccess {

    private static final String ATT_ACCESS_OBJECT = "ACCESS_OBJECT";

    private static String attributeCrypt = null;

    public SessionAccess() {
    }

    private static String getAttributeCrypt() {

        if (attributeCrypt == null) {
            attributeCrypt = Cryptography.getRandomKey();
        }
        return attributeCrypt;
    }

    private static String getAttributeName(HttpSession session) {

        if (session.getAttribute(getAttributeCrypt()) == null) {
            String randomKey = Cryptography.getRandomKey();
            session.setAttribute(getAttributeCrypt(), randomKey);
        }
        String auxSiteCrypt = session.getAttribute(getAttributeCrypt()).toString();
        return Cryptography.crypt(auxSiteCrypt, ATT_ACCESS_OBJECT);
    }

    public static void setAccessObject(Object accessObject, HttpSession session) {

        session.setAttribute(getAttributeName(session), accessObject);
    }

    public static Object getAccessObject(HttpSession session) {

        String attributeName = getAttributeName(session);
        return session.getAttribute(attributeName);
    }

    public static boolean hasAccessObject(HttpSession session) {

        return getAccessObject(session) != null;
    }

    public static void releaseAccessObject(HttpSession session) {

        String attributeName = getAttributeName(session);
        session.removeAttribute(attributeName);
    }

    public static boolean verifyPermission(HttpSession session, int levelAccess) {

        return true;
    }

}